import { useContext, useEffect } from 'react';
import { NavBar, Input, Form, Toast } from 'antd-mobile';
import { useHistory, useParams } from 'react-router-dom';

import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const [form] = Form.useForm();
  const history = useHistory();
  let { tagCode } = useParams();
  const mySdkStore = useContext(MySdkStoreContext);

  tagCode = tagCode === '0' ? undefined : tagCode;

  useEffect(async () => {
    const res = await mySdkStore.sdk.queryFavoriteTags();
    const tagInfo = res.find(item => item.code === tagCode);
    if (tagInfo) {
      form.setFieldsValue({ tagName: tagInfo.name });
    }
  }, []);

  const handleSave = () => {
    form.validateFields().then(async (value) => {
      if (!tagCode) {
        await mySdkStore.sdk.addOrUpdateFavoriteTag(value);
        Toast.show('新增成功');
        history.goBack();
      } else {
        await mySdkStore.sdk.addOrUpdateFavoriteTag({ ...value, tagCode });
        Toast.show('编辑成功');
        history.push({ pathname: `/collectionFold/${tagCode}`});
      }
    });
  }

  return (<div className="modifyCollectPage">
    <NavBar
      onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}
      right={<a onClick={handleSave}>保存</a>}>{tagCode ? '编辑' : '新增'}标签</NavBar>
    <Form form={form} style={{ margin: '16px 0' }}>
      <Form.Item name='tagName' label='标签名称' rules={[{ required: true }]}>
        <Input placeholder='请输入标签名称' maxLength={10} />
      </Form.Item>
    </Form>
  </div>)
}